package com.example.myapplication.module_notification;

import static android.content.ContentValues.TAG;

import android.annotation.SuppressLint;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;

import com.example.myapplication.R;
import com.example.myapplication.data.Notification;
import com.example.myapplication.views.OnRefreshListener;
import com.example.myapplication.views.RefreshList;
import com.google.firebase.crashlytics.buildtools.reloc.com.google.common.reflect.TypeToken;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 本fragment的作用： 从首页中动态创建，得到参数，然后进行请求列表，并渲染。
 * typeName： 通知的类型名字，比如 教务处通知，学院通知 。。。
 * typeId： 对应的Id
 */
public class ShouYeFragment extends Fragment {

    private final int MSG_GET_DATA = 1;
    private final int MSG_NO_DATA = 2;
    RefreshList listView;
    int curPage = 1;
    private String typeName;
    private Integer typeId;
    private Handler handler;
    private Integer totalPage;
    private List<Notification> notis = new ArrayList<>();

    public ShouYeFragment() {
        // Required empty public constructor
    }

    public static ShouYeFragment newInstance(String param1, Integer param2,Integer param3) {
        ShouYeFragment fragment = new ShouYeFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        args.putInt("typeId", param2);
        args.putString("typeName", param1);
        args.putInt("total",param3);
        return fragment;
    }

    @SuppressLint("HandlerLeak")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            this.typeId = getArguments().getInt("typeId");
            this.typeName = getArguments().getString("typeName");
            this.totalPage = getArguments().getInt("total")/10+1;
        }

        this.handler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                switch (msg.what) {
                    case MSG_GET_DATA:
                        notis.addAll((List<Notification>)msg.obj);
                        listView.setAdapter(new NotificationsAdapter(getContext(),notis));
                        break;
                    case MSG_NO_DATA:
                        //回退
                        break;
                }
            }
        };

        getData(curPage);
    }

    @Override
    @SuppressLint("MissingInflatedId")
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_notification, container, false);
        this.listView = view.findViewById(R.id.listView);

        this.listView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void OnRefresh(RefreshList customLv) {
                requireRefresh();
            }
        });
        this.listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE: // 当不滚动时
                        // 判断滚动到底部
                        if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
                            Log.d(TAG, "onScrollStateChanged: 到底了！");
                            if(curPage<totalPage)
                                requireMoreData();
                        }
                        break;
                }
            }
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }});
        listView.setDivider(null);
        listView.setDividerHeight(10);
        listView.setLeft(10);
        listView.setRight(10);

        return view;
    }

    public boolean requireRefresh() {
        notis.clear();
        curPage=1;
        getData(curPage);
        return false;
    }

    private void getData(int page) {

        String url = getString(R.string.httpPrefix) + "/notisOfType?type=" + this.typeName + "&page="+page;

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    //创建OkHttpClient对象
                    OkHttpClient client = new OkHttpClient();
                    //创建Request// 注意，调试时候模拟器访问电脑用10.0.2.2....

                    Request request = new Request.Builder()
                            .url(url)//访问连接
                            .get()
                            .build();
                    //创建Call对象
                    Call call = client.newCall(request);

                    Gson gson = new Gson();
                    //通过execute()方法获得请求响应的Response对象
                    Response response = call.execute();
                    if (response.isSuccessful()) {
                        ResponseBody body = response.body();
                        String string = body.string();
                        List<Notification> list = gson.fromJson(string, new TypeToken<List<Notification>>() {
                        }.getType());
                        if(list!=null){
                            //可以正常反序列化//
                            for (int i = list.size() - 1; i >= 0; i--) {
                                Log.e(TAG, "shouye--: " + list.get(i));
                            }
                            Message message = new Message();
                            message.what = MSG_GET_DATA;
                            message.obj = list;
                            handler.sendMessage(message);
                        }else{
                            Message message = new Message();
                            message.what = MSG_NO_DATA;
                            handler.sendMessage(message);
                        }
                    }
                } catch (Exception e) {
                    Log.d(TAG, "run: errrrrrrrrrrrrrrrrrrr");
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void requireMoreData() {
        getData(++curPage);
    }



}